/* eslint-disable no-template-curly-in-string */
/**
 * @Description:electron-builder 构建
 * @Author: lishibin
 * @Date: 12:19 2022/09/03
 * @version : V0.0.1-beta
 */

import type { Configuration } from 'electron-builder';

import type { AppBuilderOptions } from '../../../typing';

import os from 'node:os';

import { colors, consola } from '@vben/node-utils';

import * as builder from 'electron-builder';
import { Platform } from 'electron-builder';
// 原生模块
const nativeLib = [] as any;
// 不复制原生资源
const excludeFiles = () => nativeLib.map((r: string) => `!node_modules/${r}`);
// 原生模块资源配置
const nativeLibs = () =>
  nativeLib.map((r: string) => {
    return {
      from: `library/${r}`,
      to: `node_modules/${r}`,
      // 只复制打包平台node文件以及lib package.json 和 binding 下的js 文件
      filter: [
        '**/binding/${platform}/${arch}/**/*',
        '**/lib/**/*',
        'package.json',
        '**/binding/*.js',
      ],
    };
  });

/**
 * 公共配置
 */
const commonOptions: Configuration = {
  // 包含文件
  files: [
    'dist',
    ...excludeFiles(),
    ...nativeLibs(),
    '!node_modules',
    // window usb lib
  ],
  electronDownload: {
    mirror: 'https://registry.npmmirror.com/-/binary/electron/',
    strictSSL: false,
  },
  //  extraResources: [...extraResources()],
  // 包名规则   这里改成固定值
  //  artifactName: '${productName}-${buildVersion}.${ext}'
  artifactName: '${productName}-${version}-${platform}-${arch}.${ext}',
  //  artifactName: '${productName}-${version}-x86_32.${ext}'
};

const build = (
  cfg: AppBuilderOptions = {},
  platform: NodeJS.Platform = os.platform(),
) => {
  const targets = Platform.fromString(platform).createTarget();
  builder
    .build({
      targets,
      config: {
        ...commonOptions,
        productName: 'demo',
        win: cfg.win,
        asar: cfg.compress,
        nsis: cfg.nsis,
        artifactName: cfg.artifactName,
        directories: cfg.directories,
      },
    })
    .then((result) => {
      consola.log(
        `  ${colors.green('➜')}  ${colors.bold('Electron Builder')}: ${colors.cyan(`build electron app finished. out all file list`)}`,
      );
      result.forEach((r) => {
        consola.log(`${colors.green(r)}`);
      });
      process.exit();
    })
    .catch((error) => {
      consola.error(new Error('Electron Builder:build electron app error'));
      consola.error(error);
      process.exit(0);
    });
};
export default build;
